package org.example.com.controller;

import org.example.com.pojo.*;
import org.example.com.pojo.vo.ChatMessage;
import org.example.com.pojo.vo.ChatRequest;
import org.example.com.pojo.vo.ChatResponse;
import org.example.com.pojo.vo.ChatSession;
import org.example.com.service.ChatService;
import org.example.com.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * AI聊天机器人控制器
 */
@RestController
@RequestMapping("/chat")
public class ChatController {

    @Autowired
    private ChatService chatService;

    /**
     * 创建新的聊天会话
     */
    @PostMapping("/sessions")
    public Result createSession(@RequestParam(required = false) String title) {
        // 获取当前登录用户ID
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        
        // 如果标题为空，设置默认标题
        if (title == null || title.trim().isEmpty()) {
            title = "租房咨询 - " + System.currentTimeMillis();
        }
        
        ChatSession session = chatService.createSession(userId, title);
        return Result.success(session);
    }

    /**
     * 获取用户的所有聊天会话
     */
    @GetMapping("/sessions")
    public Result getUserSessions() {
        // 获取当前登录用户ID
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        
        List<ChatSession> sessions = chatService.getUserSessions(userId);
        return Result.success(sessions);
    }

    /**
     * 获取会话详情
     */
    @GetMapping("/sessions/{sessionId}")
    public Result getSessionById(@PathVariable String sessionId) {
        ChatSession session = chatService.getSessionById(sessionId);
        if (session == null) {
            return Result.error("会话不存在");
        }
        return Result.success(session);
    }

    /**
     * 获取会话的消息历史
     */
    @GetMapping("/sessions/{sessionId}/messages")
    public Result getSessionMessages(@PathVariable String sessionId) {
        List<ChatMessage> messages = chatService.getSessionMessages(sessionId);
        return Result.success(messages);
    }

    /**
     * 发送消息并获取AI回复
     */
    @PostMapping("/messages")
    public Result sendMessage(@RequestBody ChatRequest request) {
        // 获取当前登录用户ID
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        
        if (request.getSessionId() == null || request.getSessionId().trim().isEmpty()) {
            return Result.error("会话ID不能为空");
        }
        
        if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
            return Result.error("消息内容不能为空");
        }
        
        ChatResponse response = chatService.sendMessage(userId, request.getSessionId(), request.getMessage());
        return Result.success(response);
    }

    /**
     * 更新会话标题
     */
    @PutMapping("/sessions/{sessionId}/title")
    public Result updateSessionTitle(@PathVariable String sessionId, @RequestParam String title) {
        if (title == null || title.trim().isEmpty()) {
            return Result.error("标题不能为空");
        }
        
        chatService.updateSessionTitle(sessionId, title);
        return Result.success();
    }

    /**
     * 归档会话
     */
    @PutMapping("/sessions/{sessionId}/archive")
    public Result archiveSession(@PathVariable String sessionId) {
        chatService.archiveSession(sessionId);
        return Result.success();
    }

    /**
     * 删除会话
     */
    @DeleteMapping("/sessions/{sessionId}")
    public Result deleteSession(@PathVariable String sessionId) {
        chatService.deleteSession(sessionId);
        return Result.success();
    }
}
